import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getPerformanceInfo, updatePerformanceInfo } from '@/api/performance'
import type { DepartmentItem, AddDepartmentParams, UpdateDepartmentParams } from '@/api/types/department'
import { ElMessage } from 'element-plus'

export const useStore = defineStore('performance', () => {
    const departmentList = ref<[] |any >([])
    const loading = ref(false)

    // 获取门店列表
    const fetchDepartmentList = async (data: any) => {
        loading.value = true
        try {
            const response = await getPerformanceInfo(data)
            if (response.code === '200') {
                departmentList.value = response.data.info_list
            } else {
                ElMessage.error(response.msg || '获取门店业绩列表失败')
            }
        } catch (error) {
            console.error('获取门店业绩列表失败:', error)
            ElMessage.error('获取门店业绩列表失败')
        } finally {
            loading.value = false
        }
    }

    // 编辑
    const updateDepartmentAction = async (data: any) => {
        try {
            const response = await updatePerformanceInfo(data)
            if (response.code === '200') {
                ElMessage.success(response.msg || '修改成功')
                await fetchDepartmentList(data.recordmonth)
                return true
            } else {
                ElMessage.error(response.msg || '修改失败')
                return false
            }
        } catch (error) {
            console.error('编辑门店业绩失败:', error)
            ElMessage.error('编辑门店业绩失败')
            return false
        }
    }

    return {
        departmentList,
        loading,
        fetchDepartmentList,
        updateDepartment: updateDepartmentAction,
    }
})
